package cn.zb.zbrhback.auth.interceptor;

import cn.zb.zbrhback.auth.annotation.ZBPermission;
import cn.zb.zbrhback.auth.mapper.PermissionMapper;
import cn.zb.zbrhback.basic.util.LoginMap;
import cn.zb.zbrhback.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthPermInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Employee employee = LoginMap.map.get(token);
        if(Objects.isNull(employee)){//未登录
            response.getWriter().print("{\"success\":false,\"message\":\"noLogin\"}");
            return false;    // 登录信息为空，不放行
        }
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            // 2.1 判断方法上面是否有权限注解，如果没有，说明不需要权限都能访问，直接放行
            // 获取@RonghuaPermission，看存不存在这个注解
            ZBPermission methodAnnotation = method.getAnnotation(ZBPermission.class);
            if(Objects.isNull(methodAnnotation)){   // 注解为空，说明当前方法的访问不需要权限，直接放行
                return  true;
            }
            // 2.2 获取当前用户所有的权限
            List<String> sns = permissionMapper.loadSnsByUserId(employee.getId());
            // 2.3 获取当前资源的访问权限
            String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();
            // 2.4 用户拥有的权限中是否包含这个资源的权限，包含就放行，不包含就拦截并返回错误信息
            if(!sns.contains(sn)){
                response.getWriter().print("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
